<template>
    <div>
        <global-tables
            @handleAllSelect="handleAllSelect"
            @changePage="handleChangePage"
            :list="list"
            :total="total"
            :loading="loading"
            :columns="columns"
            :current="search.Page"
        >
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <div>
                            <Button v-if="isAddBtn" class="features-btn" @click="handleBtnClick(null,'add')">
                                <Icon type="md-add" size="18"/>新建
                            </Button>
                            <Button v-if="isDelete" class="features-btn btn-auto-m" @click="handleBtnClick(null,'delete')">
                                <Icon type="md-trash" size="17"/>删除
                            </Button>
                            <Button v-if="isProhibit" class="features-btn btn-auto-m" @click="handleBtnClick(null,'on')">
                                <Icon type="ios-unlock-outline" size="17"/>启用
                            </Button>
                            <Button v-if="isProhibit" class="features-btn btn-auto-m" @click="handleBtnClick(null,'off')">
                                <Icon type="ios-lock-outline" size="17"/>停用
                            </Button>
                        </div>
                    </div>
                    <div class="table-top-wrap-bottom">
                        <div>
                            <input type="text" class="style-input" @keyup.enter="handleSearch" v-model="search.keyword" placeholder="请输入品牌名称">
                            <i-input style="display:none"></i-input>
                        </div>
                        <div>
                            <Button icon="ios-search" @click="handleSearch" class="search-btn">搜索</Button>
                        </div>
                    </div>
                </div>
            </Form>
        </global-tables>
        <Modal :mask-closable="false" v-model="isModal" :title="ModalTitle" width="600">
            <div v-if="isModal">
                <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                    <Row>
                        <i-col :lg="{ span: 16}">
                            <FormItem label="活动名称" prop="ActivityName">
                                <i-input v-model="formItem.ActivityName" placeholder="请输入活动名称"></i-input>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 14}">
                            <FormItem label="活动类别">
                                <RadioGroup v-model="formItem.Discount" @on-change="Category">
                                    <Radio label="1">折上折</Radio>
                                    <Radio label="2">买赠同品</Radio>
                                    <Radio label="3">送现金</Radio>
                                </RadioGroup>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 16}">
                            <FormItem label="折扣" prop="DiscountNumber" v-if="isDiscount">
                                <i-input v-model="formItem.DiscountNumber" :maxlength="3" placeholder="请输入折扣" number></i-input>/* 如85折请输入8.5，注意只支持一位小数 */
                            </FormItem>
                        </i-col>
                    </Row>

                    <Row>
                        <i-col :lg="{ span:20}">
                            <FormItem label="选择" prop="Choice" v-if="isChoice">
                                买
                                <i-input v-model="formItem.Choice.buy" placeholder="请输入件数" style="width: 115px;" number></i-input>,件
                                赠
                                <i-input v-model="formItem.Choice.Gift" placeholder="请输入件数" style="width: 115px;" number></i-input>&nbsp;件
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 16}">
                            <FormItem label="选择红包" prop="Envelopes" v-if="isEnvelopes">
                                <!-- <i-input v-model="formItem.Envelopes" placeholder value="0"></i-input> -->
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 20}">
                            <FormItem label="购买门槛" prop="Threshold" v-if="isThreshold">
                                <i-input v-model="formItem.Threshold" placeholder="请输入件数" style="width: 280px;" number></i-input>&nbsp;件
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span:17}">
                            <FormItem label="限购件数" prop="Number">
                                <i-input v-model="formItem.Number" placeholder="请输入件数" number style="width: 280px;"></i-input>&nbsp;件
                                /* 0代表不限购 */
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 20}">
                            <FormItem label="活动开始时间" prop="StartTime">
                                <DatePicker
                                    type="datetime"
                                    format="yyyy-MM-dd HH:mm"
                                    style="width: 200px"
                                    placeholder="开始时间"
                                    v-model="formItem.StartTime"
                                    :disabled="isDisabled"
                                ></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span:20}">
                            <FormItem label="活动结束时间" prop="EndTime">
                                <DatePicker
                                    type="datetime"
                                    format="yyyy-MM-dd HH:mm"
                                    placeholder="结束时间"
                                    style="width:200px"
                                    v-model="formItem.EndTime"
                                    :disabled="isDisabled"
                                ></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 12}">
                            <FormItem label="时间控制" prop="TimeControl">
                                <!-- <CheckboxGroup v-model="formItem.TimeControl">
                                    <Checkbox :label="不限时间">不限时间</Checkbox>
                                </CheckboxGroup>-->
                                <CheckboxGroup v-model="formItem.Enable">
                                    <Checkbox :label="enble">不限时间</Checkbox>
                                </CheckboxGroup>
                            </FormItem>
                        </i-col>
                    </Row>
                    <!-- <Row>
                        <i-col :lg="{ span: 12}">
                            <FormItem label="是否启用" prop="Enable">
                                <CheckboxGroup v-model="formItem.Enable">
                                    <Checkbox :label="!enble">启用</Checkbox>
                                </CheckboxGroup>
                            </FormItem>
                        </i-col>
                    </Row>-->
                </Form>
            </div>
            <div slot="footer">
                <Button size="large" @click="handleClose">取消</Button>
                <Button type="primary" size="large" @click="handleSubmit('formItem')">确定</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
/**
 * 品牌列表
 */
import { cyclicRouting } from '@/util';
import { getModulePermission } from '@/api/user';
import GlobalTables from '@/components/GlobalTables';
//import AsyncSelect from '@/components/AsyncSelect';
import Api from './service';
export default {
    name: 'ProductsBrand',
    components: {
        GlobalTables
    },
    data() {
        return {
            /**
             *  list 表格数据
             *  itemId 对话框id : 修改的时候需要
             *  allSelectArr 多选数据 : 批量删除或者停用
             *  loading 表格加载
             *  total 表格总页
             *  formItem 表单数据 : 提交表单对应的数据
             *  ruleValidate 表单校验
             *  isDelete 删除按钮
             *  isAddBtn 添加按钮
             *  isProhibit 停用按钮
             *  isModal 对话框状态
             *  ModalTitle  对话框标题
             *  search  请求数据 : 分页 模糊搜索
             *  columns 表头
             *  validatorSupplierID 自定义校验
             */
            list: [],
            total: 0,
            itemId: '',
            loading: true,
            isDelete: false,
            isAddBtn: false,
            isAddProduct: false,
            isProhibit: false,
            isModal: false,
            allSelectArr: null,
            ModalTitle: '新建品牌',
            Discount: '1', //活动方式
            isDiscount: false, //折扣
            isChoice: false, //选择
            isEnvelopes: false, //红包
            isThreshold: false, //门槛
            enble: true,
            isDisabled: false,
            //startTimeOptions: {}, //开始日期设置
            //endTimeOptions: {}, //结束日期设置
            //starttime: '', //开始日期model
            //endtime: '', //结束日期model
            formItem: this.initFormItem(),
            search: {
                keyword: '',
                pageindex: 1,
                pagesize: 10,
                type: ''
            },
            ruleValidate: {
                ActivityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }], //ActivityCategory
                //ActivityCategory: [{ required: true, message: '请输入活动类别', trigger: 'change' }],
                DiscountNumber: [{ required: true, type: 'number', message: '请输入折扣', trigger: 'blur' }],
                Choice: [
                    {
                        required: true,
                        type: 'object',
                        fields: {
                            buy: { type: 'number', required: true, message: '请输入件数', trigger: 'blur' },
                            Gift: { type: 'number', required: true, message: '请输入件数', trigger: 'blur' }
                        }
                    }
                ],
                //Envelopes: [{ required: true, message: '请选择红包', trigger: 'change' }],
                Threshold: [{ required: true, type: 'number', message: '请输入购买件数', trigger: 'blur' }],
                Number: [{ required: true, type: 'number', message: '请输入购买件数', trigger: 'blur' }]
                //StartTime: [{ required: true, message: '请选择活动开始时间', trigger: 'change', pattern: /.+/ }],
                //EndTime: [{ required: true, message: '请选择活动结束时间', trigger: 'change', pattern: /.+/ }]
            },
            /* 表头 */
            columns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '活动名称',
                    key: 'ActName'
                },
                {
                    title: '活动类别',
                    key: 'ActType'
                },
                {
                    title: '活动内容',
                    key: 'Remark'
                },
                {
                    title: '限购件数',
                    key: 'MaxBuy'
                },
                {
                    title: '活动时间',
                    width: 300,
                    align: 'center',
                    render: (h, params) => {
                        const { IsForever } = params.row;
                        if (!IsForever) {
                            return h('div', [
                                h('p', {}, `开始时间:${params.row.BeginTime}`),
                                ('p', {}, `结束时间:${params.row.EndTime}`)
                            ]);
                        } else {
                            return h('div', [h('p', {}, '不限时间')]);
                        }
                    }
                },
                {
                    title: '活动商品',
                    key: 'GiveCount'
                },
                {
                    title: '状态',
                    render: (h, params) => {
                        const { IsForever } = params.row;
                        if (IsForever) {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'processing',
                                        text: '正常'
                                    }
                                })
                            ]);
                        } else {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'error',
                                        text: '停用'
                                    }
                                })
                            ]);
                        }
                    }
                },
                {
                    title: '操作人',
                    key: 'Modifier'
                },
                {
                    title: '操作时间',
                    width: 200,
                    align: 'center',
                    key: 'LastModifyTime'
                },
                {
                    title: '操作',
                    align: 'center',
                    width: 170,
                    render: (h, params) => {
                        const { isEdit, isAddProduct } = this;
                        return h('div', [
                            isEdit &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: '#5ab1ef',
                                            border: 'none',
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'edit');
                                            }
                                        }
                                    },
                                    '修改'
                                ),
                            isAddProduct &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: 'rgb(252, 134, 117)',
                                            border: 'none',
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'addProduct');
                                            }
                                        }
                                    },
                                    '添加商品'
                                )
                        ]);
                    }
                }
            ]
        };
    },
    methods: {
        //判断活动类别
        Category() {
            if (this.formItem.Discount == '1') {
                this.isDiscount = true;
                this.isChoice = false;
                this.isEnvelopes = false;
                this.isThreshold = false;
                this.formItem.Remark = `活动商品销售价再打${this.formItem.DiscountNumber}折`;
            } else if (this.formItem.Discount == '2') {
                this.isChoice = true;
                this.isDiscount = false;
                this.isEnvelopes = false;
                this.isThreshold = false;
                this.formItem.Remark = `买${this.formItem.Choice.buy}赠${this.formItem.Choice.Gift}`;
            } else {
                this.isDiscount = false;
                this.isChoice = false;
                this.isEnvelopes = true;
                this.isThreshold = true;
            }
        },
        //是否启用
        // IsEnable() {
        //     
        // },
        //是否不限时间
        // isDate() {
        //     

        //     if (this.formItem.Enable.length < 1) {
        //         this.isDisabled = false;
        //     } else {
        //         this.isDisabled = true;
        //     }
        // },
        /* 关闭对话框 */
        handleClose() {
            this.isModal = false;
        },
        /* 提交 */
        handleSubmit(name) {
            const { itemId } = this;
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.Category();
                    let data = {
                        ID: itemId,
                        UsedPage: '',
                        ActName: this.formItem.ActivityName,
                        ActType: this.formItem.Discount,
                        Discount: this.formItem.DiscountNumber,
                        BeginTime: this.formItem.StartTime,
                        EndTime: this.formItem.EndTime,
                        MaxBuy: this.formItem.Number,
                        BuyCount: this.formItem.Choice.buy,
                        GiveCount: this.formItem.Choice.Gift,
                        MoneyGrpID: '',
                        FixPrice: '',
                        IsForever: this.formItem.Enable.splice(1, 1).join(),
                        Remark: '11'
                    };
                    Api.addTablesItem(data).then(res => {
                        if (res.state == 'success') {
                            this.$Message.success('操作成功');
                            this.loading = true;
                            this.isModal = false;
                            this.getTablesListData();
                        } else {
                            this.$Message.error(res.message);
                        }
                    });
                }
            });
        },
        /* 供应商选择 */
        setDictionaries(item, value) {
            this.formItem[value] = item.ID + ' ';
        },
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            Api.getTablesList(data).then(res => {
                this.list = res.data.rows;
                this.loading = false;
                this.total = res.data.records;
            });
        },
        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        /* 对话框 */
        handleBtnClick(item, type) {
            this.formItem = this.initFormItem();
            if (type == 'edit' || type == 'add') {
                this.itemId = '';
                if (type == 'edit') {
                    this.itemId = item.ID;
                    this.ModalTitle = '修改品牌';
                    Api.getItemInfo({
                        id: this.itemId
                    }).then(res => {
                        this.isModal = true;
                        this.formItem.Enable = [];
                        (this.formItem.ActivityName = res.data.ActName),
                            (this.formItem.Discount = res.data.ActType),
                            (this.formItem.DiscountNumber = res.data.Discount),
                            (this.formItem.Number = res.data.MaxBuy),
                            (this.formItem.StartTime = res.data.BeginTime),
                            (this.formItem.EndTime = res.data.EndTime);
                        this.formItem.Choice.buy = res.data.BuyCount;
                        this.formItem.Choice.Gift = res.data.GiveCount;
                        //this.formItem.Threshold = res.data.
                        this.formItem.Enable.push(res.data.IsForever);
                        if (res.data.ActType == '1') {
                            this.isDiscount = true;
                            this.isChoice = false;
                            this.isEnvelopes = false;
                            this.isThreshold = false;
                        } else if (res.data.ActType == '2') {
                            this.isChoice = true;
                            this.isDiscount = false;
                            this.isEnvelopes = false;
                            this.isThreshold = false;
                        } else if (res.data.ActType == '3') {
                            this.isDiscount = false;
                            this.isChoice = false;
                            this.isEnvelopes = true;
                            this.isThreshold = true;
                        }
                    });
                } else {
                    this.isModal = true;
                    this.ModalTitle = '新建活动';
                    this.formItem.Discount = '1';
                    this.isDiscount = true;
                    this.Category();
                    this.formItem.Enable.push(this.enble);
                    this.enble = true;
                }
            } else if (type === 'off' || type === 'on') {
                let title = '';
                if (type == 'off') {
                    title = '停用';
                } else {
                    title = '启用';
                }
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要${title}吗`,
                        onOk: () => {
                            Api.setDisableEnable({
                                ids: this.allSelectArr
                                // value: type == 'off' ? 0 : 1
                            }).then(res => {
                                if (res.state == 'success') {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = '';
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info('取消成功');
                        }
                    });
                } else {
                    this.$Message.error('请选择品牌');
                }
            } else if (type === 'delete') {
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要删除吗`,
                        onOk: () => {
                            Api.DeleteForm({
                                ids: this.allSelectArr
                            }).then(res => {
                                if (res.state == 'success') {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = '';
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info('取消成功');
                        }
                    });
                } else {
                    this.$Message.error('请选择活动');
                }
            } else if (type == 'addProduct') {
                this.$router.push({
                    path: `/marketingProducts-add/${item.ID}`
                });
            }
        },
        /* 表单数据 */
        initFormItem() {
            return {
                SupplieerID: '',
                ActivityName: '',
                Discount: '1',
                DiscountNumber: '',
                Threshold: '',
                Number: '0',
                StartTime: '',
                EndTime: '',
                Choice: {
                    buy: '',
                    Gift: ''
                },
                Enable: [],
                Remark: ''
            };
        },
        /* 表格分页方法 */
        handleChangePage(type, page) {
            this.loading = true;
            if (type == 'page') {
                this.search.pageindex = page;
                this.getTablesListData();
            } else {
                this.search.pagesizeize = page;
                this.getTablesListData();
            }
        },
        /* 复选框选中 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(',');
            }
            arr = arr.join(',');
            this.allSelectArr = arr;
        }
    },
    mounted() {
        /* 获取菜单的id */
        cyclicRouting(JSON.parse(sessionStorage.getItem('user')).menuList, this.$route, id => {
            /* 按钮权限请求 */
            getModulePermission({
                roleid: JSON.parse(sessionStorage.getItem('user')).roleid,
                moduleid: id
            }).then(res => {
                /* 按钮权限赋值 */
                for (let item in res.data) {
                    if (res.data[item].name == 'add') {
                        this.isAddBtn = true;
                    } else if (res.data[item].name == 'delete') {
                        this.isDelete = true;
                    } else if (res.data[item].name == 'edit') {
                        this.isEdit = true;
                    } else if (res.data[item].name == 'onoff') {
                        this.isProhibit = true;
                    } else if (res.data[item].name == 'addProduct') {
                        this.isAddProduct = true;
                    }
                }
                /* 列表请求 */
                this.getTablesListData();
            });
        });
    }
};
</script>

<style>
</style>
